package com.xingdata.jjxc.receiver;

import jar.MessageManager;
import jar.model.RequestEntity;
import jar.tools.InstructionSet;
import jar.tools.UdpTools;

import java.io.UnsupportedEncodingException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.provider.ContactsContract.PhoneLookup;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.xingdata.jjxc.Common;
import com.xingdata.jjxc.enty.NotificationEntity;
import com.xingdata.jjxc.utils.Hud_Panid;
import com.xingdata.jjxc.utils.SharedPreTools;
import com.xingdata.jjxc.utils.SystemInfo;

public class PhoneReceiver extends BroadcastReceiver {
	private String TAG = "PhoneReceiver";
	/** 来电号码 */
	private static String _PhoneNumber = null;
	private static boolean mIncomingFlag = false;
	private NotificationEntity entity = null;
	// private UartService service;
	// 呼入0 接通1 挂断2
	private int PhoneState = 0;
	private ArrayList<byte[]> bs;
	private SmsMessage msg;

	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();
		String action = intent.getAction();
		Log.i(TAG, "action>" + action);
		if (intent.getAction().equals("android.intent.action.PHONE_STATE")) {
			TelephonyManager tManager = (TelephonyManager) context
					.getSystemService(Service.TELEPHONY_SERVICE);
			switch (tManager.getCallState()) {
			case TelephonyManager.CALL_STATE_RINGING:
				PhoneState = 0;
				entity = new NotificationEntity();
				mIncomingFlag = true;
				_PhoneNumber = intent.getStringExtra("incoming_number");
				String body = getContactName(_PhoneNumber, context);
				if (body != null && body.length() != 0) {
					// entity.setNumber(body);
					// _PhoneNumber = body;
				}

				Log.i(TAG, "发现来电 :" + _PhoneNumber);
				// if (getUartService() != null) {
				// callPhone(PhoneState, _PhoneNumber);
				// }
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK:
				PhoneState = 1;
				if (mIncomingFlag) {
					Log.i(TAG, "通话中" + _PhoneNumber);
				}
				// if (getUartService() != null) {
				// callPhone(PhoneState, _PhoneNumber);
				// }
				break;
			case TelephonyManager.CALL_STATE_IDLE:
				PhoneState = 2;
				if (mIncomingFlag) {
					Log.i(TAG, "挂断");
					mIncomingFlag = false;
				}
				// if (getUartService() != null) {
				// callPhone(PhoneState, "");
				// }
				break;
			}

		} else if (intent.getAction().equals(
				"android.provider.Telephony.SMS_RECEIVED")
				&& SharedPreTools
						.getString(context, Common.COF_NOTIFYPUSH, "9").equals(
								"0")) {
			Object[] smsObj = (Object[]) bundle.get("pdus");
			for (Object object : smsObj) {
				msg = SmsMessage.createFromPdu((byte[]) object);
				Date date = new Date(msg.getTimestampMillis());// 时间
				SimpleDateFormat format = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				String receiveTime = format.format(date);
				String mes = msg.getDisplayMessageBody();
				String body = msg.getOriginatingAddress();
				if (body != null) {
					body.replace("+86", "");
				}
				String name = getContactName(body, context);
				if (name != null && name.length() != 0) {
					body = name;
				}
				System.out.println("mes:" + mes + "   body:" + body + "  time:"
						+ msg.getTimestampMillis());
				getMessage(mes, body);
			}
			// 接收ODB数据做相应处理
		} else if (intent.getAction().equals(
				"android.net.conn.CONNECTIVITY_CHANGE")) {
			ConnectivityManager manager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mobileInfo = manager
					.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
			NetworkInfo wifiInfo = manager
					.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			NetworkInfo activeInfo = manager.getActiveNetworkInfo();
			if (activeInfo == null) {
				return;
			} else {
				WifiManager wifiManager = (WifiManager) context
						.getSystemService(Context.WIFI_SERVICE);
				WifiInfo connInfo = wifiManager.getConnectionInfo();
				UdpTools.setPhoneIP(Formatter.formatIpAddress(connInfo
						.getIpAddress()));
				Log.i(TAG, "ip 地址发生改变" + UdpTools.getPhoneIP());
			}

		}
		//
		// else if (intent.getAction().equals(UartService.EXTRA_ODB)) {
		// Bundle mBundle = intent.getExtras();
		// String strDBO = mBundle.getString(Hud_Panid.OBD_MARK_START);
		// Log.i(TAG, strDBO);
		// SharedPreTools.putString(context, Hud_Panid.OBD_MARK_START, strDBO);
		// }
	}

	private void getMessage(String mes, String body) {

		NotificationEntity mEntity = new NotificationEntity();
		mEntity.setMessage(mes);
		int inSpace = body.indexOf("+86");
		if (inSpace > -1) {
			body = body.replace("+86", "+86 ");
		}
		mEntity.setMessageForm(body);
		mEntity.setType("0");
		Log.i(TAG, mEntity.getMessage());
		MessageManager.send(Integer.parseInt(SystemInfo.getSendPORT()),
				new RequestEntity(JSON.toJSONString(mEntity),
						InstructionSet.INSTRUCTION_AUTH_MESSAGE_TO_HUD + ""));

		//
		// // 0x05 0x32 \t QQ \t 内容
		// bs = new ArrayList<byte[]>();
		// bs.add(Hud_Panid.ZXSendHudDataBeforCodeWithMessage);
		// bs.add(Hud_Panid.ZXSendHudDataBeforTypeWithCallUp);
		// bs.add(Hud_Panid.ZXSendHudDataBeforTypeWithFeedBackNewline);
		//
		// try {
		// // 昵称
		// bs.add(body.getBytes("utf-8"));
		// // \t
		// bs.add(Hud_Panid.ZXSendHudDataBeforTypeWithFeedBackNewline);
		// // 内容
		// bs.add(mes.getBytes("utf-8"));
		// bs.add(Hud_Panid.ZXSendHudDataBeforCodeWithCallUPEnd1);
		// bs.add(Hud_Panid.ZXSendHudDataBeforCodeWithCallUPEnd2);
		Log.i(TAG, "body: " + body + " message: " + mes);
		// Consumer.getInstance().add(
		// new MessageTask(getUartService(), "", StringUtil
		// .ArrayBytesCopy(bs)));
		// } catch (UnsupportedEncodingException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
	}

	/**
	 * 拼接byte数组
	 * 
	 * @param i
	 */
	private void callPhone(int i, String PhoneNumber) {
		if (PhoneNumber == null) {

			Log.e(TAG, "电话为空");
			return;

		}
		String inPos = i + "";
		switch (i) {
		case 0:
			// 呼入电话
			// 0x02+0+0x09+138-0221-2201+0x09+号码地+0x09+呼入电话
			bs = new ArrayList<byte[]>();
			try {
				bs.add(Hud_Panid.ZXSendHudDataBeforCodeWithCallUp);
				bs.add(inPos.getBytes("UTF-8"));
				bs.add(Hud_Panid.ZXSendHudDataBeforTypeWithFeedBackNewline);
				bs.add(PhoneNumber.getBytes());
				bs.add(Hud_Panid.ZXSendHudDataBeforTypeWithFeedBackNewline);
				bs.add("0".getBytes());
				bs.add(Hud_Panid.ZXSendHudDataBeforTypeWithFeedBackNewline);
				bs.add("呼入电话".getBytes("UTF-8"));
				bs.add(Hud_Panid.ZXSendHudDataBeforCodeWithCallUPEnd1);
				bs.add(Hud_Panid.ZXSendHudDataBeforCodeWithCallUPEnd2);
				// Consumer.getInstance().add(
				// new MessageTask(service, "", StringUtil
				// .ArrayBytesCopy(bs)));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

			break;
		case 1:
			// 接通 0x02 1 0x0d 0x0a
			bs = new ArrayList<byte[]>();
			try {
				bs.add(Hud_Panid.ZXSendHudDataBeforCodeWithCallUp);
				bs.add(inPos.getBytes("UTF-8"));
				bs.add(Hud_Panid.ZXSendHudDataBeforCodeWithCallUPEnd1);
				bs.add(Hud_Panid.ZXSendHudDataBeforCodeWithCallUPEnd2);
				// Consumer.getInstance().add(
				// new MessageTask(service, "", StringUtil
				// .ArrayBytesCopy(bs)));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

		case 2:
			// 挂断0x02 2 0x0d 0x0a
			bs = new ArrayList<byte[]>();
			try {
				bs.add(Hud_Panid.ZXSendHudDataBeforCodeWithCallUp);
				bs.add(inPos.getBytes("UTF-8"));
				bs.add(Hud_Panid.ZXSendHudDataBeforCodeWithCallUPEnd1);
				bs.add(Hud_Panid.ZXSendHudDataBeforCodeWithCallUPEnd2);
				// Consumer.getInstance().add(
				// new MessageTask(service, "", StringUtil
				// .ArrayBytesCopy(bs)));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

			break;

		default:
			break;
		}
	}

	// private UartService getUartService() {
	// if (service == null) {
	// service = BluetoothGattTools.getUartService();
	// }
	// return service;
	// }

	private String getContactName(String number, Context mContext) {
		if (TextUtils.isEmpty(number)) {
			return null;
		}
		final ContentResolver resolver = mContext.getContentResolver();
		Uri lookupUri = null;
		String[] projection = new String[] { PhoneLookup._ID,
				PhoneLookup.DISPLAY_NAME };
		Cursor cursor = null;
		try {
			lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
					Uri.encode(number));
			cursor = resolver.query(lookupUri, projection, null, null, null);
		} catch (Exception ex) {
			ex.printStackTrace();
			try {
				lookupUri = Uri.withAppendedPath(
						android.provider.Contacts.Phones.CONTENT_FILTER_URL,
						Uri.encode(number));
				cursor = resolver
						.query(lookupUri, projection, null, null, null);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		String ret = null;
		if (cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) {
			ret = cursor.getString(1);
		}
		cursor.close();
		return ret;
	}
}
